<?php

namespace App\Console\Commands\Shop;


use App\Enums\Common\NsqEnum;
use App\Models\ChatGroup\ChatGroupModel;
use App\Service\ChatGroup\ChatGroupService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubShopCreateCommand extends Command
{
    protected $signature = 'shop:nsq-sub-shop-create';

    protected $description = 'nsq监听门店创建';

    public function handle()
    {
        ini_set('memory_limit', '2G');

        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_RMS_SHOP_CREATE, NsqEnum::CHANNEL_TIGER_SHOP_CREATE,
                function (Message $message) {
                    $data = $message->data();

                    dump($data);
                    // 参数校验
                    if (!$this->valid($data)) {
                        $message->done();
                        return;
                    }

                    // 执行
                    $this->process($data);

                    $message->done();
                }
            );
    }

    private function valid(array $data): bool
    {
        $validator = Validator::make($data['shop'], [
            'id' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            Log::warning("NsqSubShopCreateCommand valid error:" . $validator->errors()->first(), $data);
            return false;
        }

        return true;
    }

    private function process(array $data): void
    {
        // 白名单开启，则不处理新增的店铺
        $shopIds = ChatGroupService::betaShopIds();
        if ($shopIds) {
            return;
        }

        // 需要延迟处理，开店业务还没更新shopId
        dispatch(function () use ($data) {
            // 初始化门店群聊
            (new ChatGroupService())->initGroup($data['shop']['id'], ChatGroupModel::TYPE_CUSTOMER_SERVE);
        })->delay(10);
    }
}
